<template>
    <div class="login-model" v-if="loginModelVisible" @click="hiddenLogin($event)">
        <toast-tip id="tip" v-show="tipVisible" :msg="tipMsg"></toast-tip>
        <div class="login-content">
            <!-- 标题 -->
            <div class="login-title" v-if="titleVisible">
                <i v-if="titleArrowVisible" @click="back()"></i>
                <span v-text="titleValue" @click="test()">登录</span>
                <span class="title-span-2" :class="{'color-green': resend}" v-if="titleTipVisible" v-text="countValue">58秒后重发</span>
            </div>
            <!-- 手机号 -->
            <input class="login-input login-phone border-outline" type="tel" maxlength="11" v-model="phone" v-if="phoneVisible" @input="phoneInput($event)" placeholder="请输入手机号">
            <div class="login-pic-code" v-if="picVisible"><img :src="picSrc" alt="" @click="refreshPic()"></div>
            <!-- 图片验证码 -->
            <input class="login-input login-pic border-outline" type="text" maxlength="4" v-model="picCode" v-if="picCodeVisible" @input="picCodeInput($event)" placeholder="请输入图形验证码">
            <!-- 协议 -->
            <div class="login-protocol" v-if="titleProtocolVisible">
                <i :class="{'login-agree': loginAgree}" @click="protocolSelect"></i>
                <p>阅读并同意 <span>《Gofun注册及租赁服务协议》</span> </p>
            </div>
            <!-- 6个好兄弟 -->
            <div class="login-code" v-if="codeBoxVisible">
                <input class="login-code-item border-outline" :class="{'login-code-item-red': redBorder1}" type="tel" maxlength="1" v-focus :autofocus="loginFocus1" v-model="code1" @input="codeInput1($event)">
                <input class="login-code-item border-outline" :class="{'login-code-item-red': redBorder2}" type="tel" maxlength="1" :autofocus="loginFocus2" v-model="code2" @input="codeInput2()">
                <input class="login-code-item border-outline" :class="{'login-code-item-red': redBorder3}" type="tel" maxlength="1" :autofocus="loginFocus3" v-model="code3" @input="codeInput3()">
                <input class="login-code-item border-outline" :class="{'login-code-item-red': redBorder4}" type="tel" maxlength="1" :autofocus="loginFocus4" v-model="code4" @input="codeInput4()">
                <input class="login-code-item border-outline" :class="{'login-code-item-red': redBorder5}" type="tel" maxlength="1" :autofocus="loginFocus5" v-model="code5" @input="codeInput5()">
                <input class="login-code-item border-outline" :class="{'login-code-item-red': redBorder6}" type="tel" maxlength="1" :autofocus="loginFocus6" v-model="code6" @input="codeInput6()">
            </div>
            <!-- 下一步 -->
            <div class="login-btn"><button class="border-outline" :class="{ 'green-bg': stepBg }" type="button" v-text="stepValue" @click="nextStep">下一步</button><i v-if="loginArrowVisible"></i></div>
        </div>
        <!-- content 结束 -->
    </div>
</template>

<script>
import qs from "qs"
import ToastTip from "../components/ToastTip"
export default {
    directives: {
       focus: {
        // 指令的定义
        inserted: function (el) {
                el.focus()
            }
        }
    },
    mounted () {
        // 开城列表
        this.cityListFn();

        let config = {
            // headers:{"Content-Type": "multipart/form-data"}
            headers:{"Authorization": this.global.getCookie("token")}
        };
        console.log(config);

        // this.global.tokenCheck();

        // token是否过期
        this.axios.post("/user/tokenValidate.json", qs.stringify({
            "Authorization": sessionStorage.token,
        }),config)
        .then(res => {
            console.log(res);
        })
    },
    methods: {
        setCookie(name, value) {
            var days = 30;
            var exp = new Date();
            exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
            document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
            console.log(document.cookie);
        },
        getCookie(name) {
            var arr,
                reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
            if (arr = document.cookie.match(reg))
                return unescape(arr[2]);
            else
                return null;
        },
        delCookie(name) {
            var exp = new Date();
            exp.setTime(exp.getTime() - 1);
            var cval = this.getCookie(name);
            if (cval != null)
                document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
        },
        // 手机号change
        phoneInput (e) {
            var phone = e.target.value;
            console.log(phone);
            if (this.phoneCheck(phone) && this.loginAgree) {
                this.stepBg = true;
                this.canClick = true;
            }
        },
        picCodeInput () {
            if (this.picCode.length == 4) {
                this.stepBg = true;
                this.canClick = true;
            }
        },
        phoneCheck (phone) {
            var phonePatt = /^1\d{10}$/g;
            return phonePatt.test(phone);
        },
        // 协议选取
        protocolSelect () {
            this.loginAgree = !this.loginAgree;
            if (this.phoneCheck(this.phone) && this.loginAgree) {
                this.stepBg = true;
                this.canClick = true;
            }
        },
        codeInput1 (e) {
            console.log(true);
            this.loginFocus2 = true;
            e.target.focus();
            $(".login-code-item:eq(1)").focus();
        },
        codeInput2 () {
            this.loginFocus3 = true;
            $(".login-code-item:eq(2)").focus();
        },
        codeInput3 () {
            this.loginFocus4 = true;
            $(".login-code-item:eq(3)").focus();
        },
        codeInput4 () {
            this.loginFocus5 = true;
            $(".login-code-item:eq(4)").focus();
        },
        codeInput5 () {
            this.loginFocus6 = true;
            $(".login-code-item:eq(5)").focus();
        },
        codeInput6 () {
            $(".login-code-item:eq(6)").blur();
            console.log(6);
            console.log(this.code1);
            if (this.code1 && this.code2 && this.code3 && this.code4 && this.code5) {
                console.log("集齐六福");
                this.stepBg = true;
                this.codeTotal = this.code1 + this.code2 + this.code3 + this.code4 + this.code5 + this.code6;
            }
        },
        // 下一步
        nextStep () {
            let _this = this;
            if (this.stepState == 1) {
                if (this.canClick) {

                    this.axios.post("/app/wechatRegist/smsCodeV1.json", qs.stringify({
                        sim: this.phone,
                        isPic: this.isPic,
                        smsType: "wechatRegist",
                        sourceFor: "wx-h5-uc",

                    }))
                    .then( res => {
                        console.log(res);
                        if (res.data.code == 200) {
                            this.phoneVisible = false;
                            this.titleProtocolVisible = false;
                            this.titleValue = "输入验证码";
                            this.titleTipVisible = true;
                            this.codeBoxVisible = true;
                            this.stepValue = "登录";
                            this.loginArrowVisible = false;
                            this.stepBg = false;
                            this.stepState = 3;

                            // 倒计时
                            this.countDown(res.data.modelData.second);
                        }else if (res.data.code == 3203) {

                            this.titleArrowVisible = true;
                            this.titleValue = "输入图形验证码";
                            this.phoneVisible = false;
                            this.titleProtocolVisible = false;
                            this.picVisible = true;
                            this.picCodeVisible = true;
                            this.stepBg = false;
                            this.stepState = 2;
                            this.isPic = "y";

                            this.picSrc = this.baseUrl + "/app/wechatRegist/getPicCode.json?updateCode=0" + "&sim=" + this.phone + "&num=" + Date.now();
                        } else {
                            this.loginToast(res.data.desc);
                        }

                    })

                } else { alert("什么都不输，不要乱点！"); return; }
            } else if (this.stepState == 2) {
                if (this.canClick) {
                    this.axios.post("/app/wechatRegist/smsCodeV1.json", qs.stringify({
                        sim: this.phone,
                        isPic: this.isPic,
                        smsType: "wechatRegist",
                        picCode: this.picCode,
                        sourceFor: "wx-h5-uc",
                    }))
                    .then(res => {
                        if (res.data.code == 200) {
                            this.titleValue = "输入验证码";
                            this.titleTipVisible = true;
                            this.picVisible = false;
                            this.picCodeVisible = false;
                            this.codeBoxVisible = true;
                            this.stepValue = "登录";
                            this.loginArrowVisible = false;
                            this.stepBg = false;
                            this.stepState = 3;
                        } else {
                            alert(res.data.desc);
                            this.picCode = "";
                        }
                    })
                }
            } else if (this.stepState == 3) {
                if ((this.codeTotal).length == 6) {

                    this.axios.post("/user/login.json", qs.stringify({
                        sim: this.phone,
                        code: this.codeTotal,
                        isPic: this.isPic,
                        sourceFor: "wx-h5-uc",
                    }))
                    .then(res => {
                        // 跳转路由
                        // this.$router.push({path: "QualityCertification", params: {}});

                        console.log(res.data.code);
                        if (res.data.code == 200) {
                            this.loginModelVisible = false;
                            this.$emit("hiddenB", 1);

                            this.setCookie("token", res.data.modelData.token);
                            sessionStorage.token = 1;
                            _this.global.token = res.data.modelData.token;

                            sessionStorage.token = res.data.modelData.token;

                            // 新用户
                            if (res.data.modelData.type == 1) {
                                console.log("cookie1", document.cookie);
                                console.log(1);
                                this.axios.post("/user/weixinConnect.json", qs.stringify({
                                    access_token: this.global.token,
                                }))
                                .then(res => {
                                    this.sessionAndWeixin(res);
                                    this.stepValue = "type=1" + res.data.modelData.userWeixin.accessToken;
                                })

                            // 老用户
                            } else if (res.data.modelData.type == 2) {
                                console.log(2);
                                console.log("cookie2", document.cookie);
                                this.axios.post("/user/refreshToken.json",qs.stringify({
                                    access_token: this.global.token,
                                }))
                                .then(res => {
                                    this.sessionAndWeixin(res);
                                    this.stepValue = "type=1" + res.data.modelData.userWeixin.refreshToken;
                                })
                            }
                        } else {
                            alert(res.data.desc);
                            this.redBorder1 = true;
                            this.redBorder2 = true;
                            this.redBorder3 = true;
                            this.redBorder4 = true;
                            this.redBorder5 = true;
                            this.redBorder6 = true;
                        }
                    })
                }
            }
        },
        // 关闭登录窗
        hiddenLogin (e) {
            if (e.target.className == "login-model" ) {
                this.loginModelVisible = false;
            }
        },
        // 刷新验证图片
        refreshPic () {
            this.picSrc = this.baseUrl + "/app/wechatRegist/getPicCode.json?updateCode=0" + "$sim=" + this.phone + "&num=" + Date.now();
        },
        // 关联微信、存accessToken
        sessionAndWeixin (res) {
            if (res.data.code == 200) {
                let weixinFlag = res.data.modelData.userWeixin.weixinFlag;
                if (weixinFlag == 1) {
                    this.tipMsg = "手机号必须是 与公众号相关联的微信 绑定的手机号。"
                } else if (weixinFlag == 2) {
                    sessionStorage.accessToken = res.data.modelData.accessToken;
                    sessionStorage.refreshToken = res.data.modelData.refreshToken;

                    this.topBannerFn();
                    this.currentOrderFn();

                    // this.loginModelVisible = false;
                }
            }
        },
        // 顶部banner提示
        topBannerFn () {
            console.log("globalToken:", this.global.token);

            this.axios.post("/order/getBannerList.json", qs.stringify({
                cityCode: "010",
                access_token: this.global.token,

            })).then(res => {
                console.log(res);
                if (res.data.code == 200) {
                    this.$emit("hiddenB", 2);
                    // cardState 身份证状态
                    // licenseState 驾驶证状态
                    // DepositState 押金状态
                    // orderPeccancyState 违章
                    // orderForfeitState 罚款
                    // userState 账户冻结
                    // orderState 未支付订单
                    // cancelOrderTomanyState 取消订单次数过多
                    // authMaxCountState 认证过于频繁下月再试
                }
            })
        },
        // 当前订单
        currentOrderFn () {
            this.axios.post("/order/currentOrder.json", qs.stringify({
                access_token: sessionStorage.token,
            })).then(res => {
                console.log(res);
            })
        },
        // 用车资格
        canUseFn () {
            this.axios.post("/upgrade/verify.json",qs.stringify({

            })).then(res => {

            })
        },
        // 切换城市
        cityListFn () {
            this.axios.post("/car/cityList.json",
                qs.stringify(
                {
                cityCode: "010",
            }
            )
                ).then(res => {
                console.log(res);
            })
        },

        // 回退
        back () {
            if (this.titleValue == "输入图形验证码") {
                this.titleValue = "登录";
                this.titleTipVisible = false;
                this.picVisible = false;
                this.picCodeVisible = false;
                this.codeBoxVisible = true;
                this.stepValue = "下一步";
                this.loginArrowVisible = false;
                this.stepBg = false;
                this.stepState = 1;
            }
        },

        // 倒计时
        countDown (second) {
            var cnt = second;
            var timer = setInterval(() => {
              this.countValue = cnt + "秒后重发";
              cnt--;
              if (cnt <= 0) {
                this.countValue = "重发验证码";
                clearInterval(timer);
              }
            }, 1e3)
        },
        loginToast(lMsg) {
            alert(lMsg);
            this.tipMsg = lMsg;
            this.tipVisible = true;
        },
    },
    data () {
        return {
            baseUrl: "http://47.93.34.85:8184",
            token: "",
            loginModelVisible: true,
            tipMsg: "测试",
            tipVisible: true,

            // 标题变量
            titleVisible: true,
            titleValue: "登录",
            titleArrowVisible: false,
            titleTipVisible: false,
            titleTipContent: "",

            resend: false,
            titleProtocolVisible: true,

            // 输入手机号
            phone: "",
            phoneVisible: true,
            loginAgree: false,

            // 图片验证码
            isPic: "n",
            picSrc: "",
            picVisible: false,
            picCodeVisible: false,
            picCode: "",
            updateCode: "",
            // 验证码
            countTime: "",
            countValue: "",
            codeBoxVisible: false,
            code1: "",
            code2: "",
            code3: "",
            code4: "",
            code5: "",
            code6: "",
            codeTotal: "",

            loginFocus1: true,
            loginFocus2: false,
            loginFocus3: false,
            loginFocus4: false,
            loginFocus5: false,
            loginFocus6: false,

            redBorder1: false,
            redBorder2: false,
            redBorder3: false,
            redBorder4: false,
            redBorder5: false,
            redBorder6: false,

            // 步骤
            stepValue: "下一步",
            canClick: false,
            stepState: 1,
            stepBg: false,
            loginArrowVisible: true,
        }
    }
 }
</script>

<style scoped>
    .login-model {
        text-align: center;
        position: absolute;
        top: 0; right: 0; bottom: 0; left: 0;
        z-index: 999;

        background: rgba(0,0,0,0.30);
    }
    .login-content {
        width: 600px;
        height: 540px;
        overflow: hidden;
        background-color: #fff;

        position: absolute;
        top: 0; right: 0; bottom: 0; left: 0;
        margin: auto;

        background: #fff;
        box-shadow: 0 10px 20px 0 rgba(0,0,0,0.10);
        border-radius: 10px;
    }
    .login-title {
        height: 88px;
        line-height: 88px;
        background-color: #f5f5f5;
        position: relative;

        font-family: PingFangSC-Regular;
        font-size: 32px;
        color: #333;
        letter-spacing: 0;
    }
    .login-title i {
        display: block;
        width: 15px;
        background-color: #ddd;
        height: 24px;

        position: absolute;
        top: 34px;
        left: 30px;
    }
    .title-span-2 {
        position: absolute;
        top: 24px;
        right: 30px;
        line-height: 40px;

        font-family: PingFangSC-Regular;
        font-size: 28px;
        color: #b4b4b4;
        letter-spacing: 0;
    }
    .login-title .color-green {
        color: #0db95f;
    }
    .login-pic-code {
        /*width: 212px;*/
        height: 100px;
        margin-top: 42px;
    }
    .login-pic-code img {
        width: 212px;
        height: 100px;
        margin: 0 auto;
        background-color: #eee;
    }
    .login-input {
        width: 360px;
        height: 70px;
        padding-bottom: 10px;
        margin: 68px 0;
        border-bottom: 2px solid #0db95f;
        text-indent: 20px;

        font-family: PingFangSC-Regular;
        font-size: 40px;
        color: #333;
        letter-spacing: 0;
    }
    .login-input::-webkit-input-placeholder{
        color: #aaa;
        /*color: #989a9c;*/
    }
    .login-phone {
        text-indent: 50px;
    }
    .login-pic {
        text-indent: 0;
        margin-top: 20px;
        margin-bottom: 56px;
        text-align: center;
    }
    .login-green {
        background: #0db95f;
    }
    .login-protocol {
        height: 24px;
        text-align: center;
        margin-bottom: 62px;

        font-family: PingFangSC-Regular;
        font-size: 24px;
        color: #aaa;
        letter-spacing: 0;
        line-height: 24px;
    }
    .login-protocol i {
        display: inline-block;
        width: 24px;
        height: 24px;
        line-height: 24px;
        margin-top: -3px; /*no*/
        margin-right: 10px;
        vertical-align: middle;

        background-color: #ccc;
    }
    .login-protocol .login-agree {
        background-color: #0db95f;
    }
    .login-protocol p {
        display: inline-block;
        height: 24px;
        line-height: 24px;
    }
    .login-protocol span {
        color: #0db95f;
    }
    .login-btn {
        height: 100px;
        text-align: center;

        position: relative;
    }
    .login-btn button {
        width: 480px;
        height: 100px;

        background: #dcdcdc;
        border-radius: 50px;

        font-family: PingFangSC-Regular;
        font-size: 32px;
        color: #fff;
        letter-spacing: 0;
    }
    .login-btn .green-bg {
        background: #0db95f;
    }
    .login-btn i {
        display: block;
        width: 15px;
        height: 24px;
        background-color: #ccc;

        position: absolute;
        top: 38px;
        right: 153px;
    }
    .login-code {
        margin: 106px 62px 94px 62px;
        display: flex;
        justify-content: space-between;
    }
    .login-code-item {
        width: 66px;
        height: 92px;
        line-height: 88px;
        /*padding-top: 20px;*/
        text-align: center;

        background: #fafafa;
        border: 2px solid #eee;
        border-radius: 10px;

        font-family: PingFangSC-Regular;
        font-size: 40px;
        color: #696969;
        letter-spacing: 0;
    }
    .login-code-item:last-of-type {
        margin-right: 0;
    }
    .login-code-item:focus {
        background: #fafafa;
        border: 4px solid #0db95f;
        border-radius: 10px;
    }
    .login-code-item-red {
        background: #fafafa;
        border: 2px solid #f26050;
        border-radius: 10px;
    }
    #tip {
        position: absolute;
        top: 0;
        left: 15%;
        z-index: 1000!important;
        width: 70% !important;
        height: 40px !important;
    }
</style>
